package org.gpf.game.tank.offline;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.List;

/**
 * 子弹类
 * @author gaopengfei
 * @date 2015-5-3 下午5:29:31
 */
public class Missile {

	private static final int X_SPEED = 10;
	private static final int Y_SPEED = 10; 			// 子弹的速度
	
	public static final int MISSILE_WIDTH = 10;		// 子弹宽高
	public static final int MISSILE_HEIGHT = 10;
	
	int x,y; 						// 位置
	Tank.Direction dir; 			// 方向
	
	private boolean good;			// 子弹具有敌方和我方的区别
	
	private boolean live = true;	// 子弹默认是活着的
	private TankClient tc;			
	public boolean isLive() {
		return live;
	}

	public Missile(int x, int y, Tank.Direction dir) {
		this.x = x;
		this.y = y;
		this.dir = dir;
	}
	
	public Missile(int x,int y,Tank.Direction dir,boolean good,TankClient tc) {
		this(x, y, dir);
		this.tc = tc;
		this.good = good;
	}
	
	/**
	 * 子弹拥有把自己画出来的方法
	 * @param g 画笔
	 */
	public void draw(Graphics g){
		
		if (!live){
			tc.missiles.remove(this);
			return;
		}
		
		Color c = g.getColor();
		g.setColor(Color.MAGENTA);
		g.fillOval(x, y, 10, 10);
		g.setColor(c);						// 将颜色重新设置回来
		
		move();
	}

	private void move() {
		
		switch (dir) {
		case L:
			x -= X_SPEED;
			break;
		case LU:
			x -= X_SPEED; // 这样写实际上是不精确的，它的速度是x和y方向的矢量和
			y -= Y_SPEED;
			break;
		case U:
			y -= Y_SPEED;
			break;
		case RU:
			x += X_SPEED;
			y -= Y_SPEED;
			break;
		case R:
			x += X_SPEED;
			break;
		case RD:
			x += X_SPEED;
			y += Y_SPEED;
			break;
		case D:
			y += Y_SPEED;
			break;
		case LD:
			x -= X_SPEED;
			y += Y_SPEED;
			break;
		default:
			break;
		}
		
		// 判断子弹是否出界，设置子弹是否存活
		if (x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y > TankClient.GAME_HEIGHT) {
			live = false;
		}
		
	}
	
	/**
	 * 获取子弹的矩形模型
	 * @return
	 */
	public Rectangle getRect(){
		
		return new Rectangle(x, y, MISSILE_WIDTH, MISSILE_HEIGHT);
	}
	
	/**
	 * 判断子弹是否击中坦克(两个矩形是否相交)、并且是敌我双方
	 * @param t
	 * @return
	 */
	public boolean hitTank(Tank t){
		
		if(this.live && this.getRect().intersects(t.getRect()) && t.isLive() && this.good!=t.isGood()){
			if (t.isGood()) {
				t.setLife(t.getLife()-5);	// 击中一次生命值减5
				if (t.getLife()<=0) t.setLive(false);
			}else {
				t.setLive(false);
			}
			this.live = false;
			
			Explode e = new Explode(x, y, tc);	// 击中坦克的时候产生一个爆炸
			tc.explodes.add(e);
			return true;
		}
		return false;
	}
	
	/**
	 * 打击一组坦克
	 * @param tanks
	 * @return
	 */
	public boolean hitTanks(List<Tank> tanks){
		
		for (int i = 0; i < tanks.size(); i++) {
			if (hitTank(tanks.get(i))) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 子弹撞墙
	 * @param w 被撞的墙
	 * @return	撞到墙返回true，没有撞到返回false
	 */
	public boolean hitWall(Wall w){
		
		if(this.live&&this.getRect().intersects(w.getRect())){
			this.live = false;
			return true;
		}
		return false;
		
	}
}
